package com.scalar.chiptrack.adaptor.smic;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.users.VendorAdaptor;
import com.scalar.chiptrack.users.dao.AdaptorSetUpDAO;
import com.scalar.ScalarException;
import com.enterprisedt.net.ftp.FTPClient;
import com.enterprisedt.net.ftp.FTPTransferType;
import com.enterprisedt.net.ftp.FTPConnectMode;

import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: Sudhakar
 * Date: May 1, 2007
 * Time: 4:01:06 PM
 */
public class SMICFtpAdaptor extends JobHandler implements AdaptorConstants
{

    private static final String HOST = "ftp.smics.com";
    private static final int SOURCE_WIP_PORT = 21;
    private static final String FILE_EXTN = ".CSV";
    public static final String FILE_NAME_SMIC_WIP = "SMIC_WIP";
    public static final String ADAPTOR_NAME = "SMIC_FAB";

    private String m_wipdir = "/Wip report/";

    private Logger m_adaptorLogger  = null;
    private String m_dataOutputDir  = null;
    private String m_username       = null;
    private String m_password       = null;
    private int    m_adaptor_id     = -1;

    public SMICFtpAdaptor() throws Exception
    {
        try
        {
            /**
             * Getting the vendor username and password by passing vendorname and location type
             */
            VendorAdaptor vendorAdaptor = AdaptorSetUpDAO.getVendorAdaptorDetailsByVendorNameAndLocation(VENDOR_NAME_SMIC, WIP_TYPE_FAB);

            m_username = vendorAdaptor.getUserId();
            m_password = vendorAdaptor.getPassWord();
            m_dataOutputDir = vendorAdaptor.getOutPutDirectory();

            if ( m_dataOutputDir != null )
            {
                if (m_dataOutputDir.endsWith("/") || m_dataOutputDir.endsWith("\\"))
                {
                    m_dataOutputDir = m_dataOutputDir + m_username;
                }
                else
                {
                    m_dataOutputDir = m_dataOutputDir + "/" + m_username;
                }
               AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );
               m_adaptorLogger = AdaptorUtils.getAdaptorLogger(m_dataOutputDir, VENDOR_NAME_SMIC);
              AdaptorUtils.setLogger( m_adaptorLogger);
            }
        }
        catch (ScalarException se)
        {
            log("ERROR!! ERROR!! ERROR!! Exception while loading SMIC Adaptor Username, Password details from database, Exception: " + se);
            throw se;
        }
    }


    public static void main(String[] args) throws Exception
    {
        new SMICFtpAdaptor().execute();
    }


    public void execute() throws Exception
    {
       try
        {
            m_adaptor_id = AdaptorRunInfo.saveAdaptorLastUpdatedStatus( CONSTANT_ADAPTOR, ADAPTOR_NAME, CONSTANT_SUCCESS, -1);

            //Print the header details
            AdaptorUtils.printHeader(VENDOR_NAME_SMIC , CONSTANT_ADAPTOR);

            AdaptorUtils.removeOldFiles( m_dataOutputDir, m_adaptorLogger );

            FTPClient ftp = login(HOST, SOURCE_WIP_PORT, m_username, m_password);

            if (ftp != null)
            {
                log("Successfully logged in to " + HOST);
                System.out.println("Successfully logged in to " + HOST);

                // Download files
                ftp.chdir(m_wipdir);
                log("Remote directory changed to " + m_wipdir);
                System.out.println("Remote directory changed to " + m_wipdir);

                //downloading Wip file
                downloadWipFile(ftp);

                // logout from the site
                logout(ftp);

                log("\nSuccessfully logged out from SMIC FTP site");
                System.out.println("\nSuccessfully logged out from SMIC FTP site");
            }
            else
            {
                log("Unable to login to the SMIC FTP site");
                throw new ScalarException("Unable to login to the SMIC FTP site");
            }
        }
        catch ( Exception e )
        {
            AdaptorUtils.removeOldFiles(m_dataOutputDir, m_adaptorLogger);
            AdaptorRunInfo.updatedAdaptorStatus( CONSTANT_FAILURE, m_adaptor_id);
            System.out.println("Exception while trying to connect and read data from " + HOST +" site: " + e);
            log("Exception while trying to connect and read data from " + HOST +" site: " + e);
            e.printStackTrace();
            throw e;
        }
    }

    /**
     *
     * @param host
     * @param port
     * @param m_username
     * @param m_password
     * @return
     * @throws Exception
     */
    private FTPClient login(String host, int port, String m_username, String m_password) throws Exception
    {
        FTPClient ftp = null;

        try
        {
            ftp = new FTPClient(host, port);
            ftp.login(m_username, m_password);
            ftp.debugResponses(false);
            ftp.setType(FTPTransferType.BINARY);
            ftp.setConnectMode(FTPConnectMode.PASV);
        }
        catch (Exception e)
        {
            log("Could Not able to connect to the SMIC FTP site, Exception : " + e);
            throw new ScalarException("Could Not able to connect to the SMIC FTP site");
        }

        return ftp;
    }
    /**
     *
     * @param ftp
     * @throws Exception
     */
    private void downloadWipFile(FTPClient ftp) throws Exception
    {
        String[] fileListings = ftp.dir();

        if ((fileListings == null) || (fileListings.length == 0))
        {
            return;
        }

        byte[] buf = null;
        String tempFileName = null;
        FileOutputStream fileOutputStream = null;
        try
        {
            System.out.println( "\tDownloading SMIC Wip file...." );
            for (int k = 0; k < fileListings.length; k++)
            {
                if (fileListings[k].startsWith(FILE_NAME_SMIC_WIP))
                {
                    if (tempFileName == null)
                    {
                        tempFileName = fileListings[k];
                    }
                    else
                    {
                        java.util.Date date1 = ftp.modtime(tempFileName);
                        java.util.Date date2 = ftp.modtime(fileListings[k]);
                        if (date2.compareTo(date1) > 0)
                        {
                            tempFileName = fileListings[k];
                        }
                    }
                }
            }
            if (tempFileName != null)
            {
                log("\ndownloading file " + tempFileName + " to " + m_dataOutputDir + " directory... ");
                //System.out.println("\ndownloading file " + tempFileName + " to " + m_dataOutputDir + " directory... ");
                 if ( m_adaptor_id > 0 )
                {
                    AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , tempFileName.substring(0, tempFileName.indexOf(".") ), FILE_EXTN_CSV, StringUtils.formatDateToString(ftp.modtime(tempFileName), "MM/dd/yyyy HH:mm:ss" ) ) ;
                }
                buf = ftp.get(tempFileName);
                int tempLength = tempFileName.lastIndexOf('.');
                tempFileName = tempFileName.substring(0, tempLength);
                tempFileName = tempFileName.toUpperCase() +"_" + AdaptorUtils.getTimeAsString() + FILE_EXTN;
                fileOutputStream = new FileOutputStream(m_dataOutputDir + "/" + tempFileName, false);
                fileOutputStream.write(buf);
                fileOutputStream.flush();
                log("\nDone... ");
                System.out.println("Done... ");
            }

        }
        catch (IOException e)
        {
            log( "Exception while downloading......... " + e );
            throw e;
        }

        finally
        {
            if (fileOutputStream != null)
            {
                try
                {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                }
                catch (IOException ignore) {
                }
            }
        }
    }

    /**
     *
     * @param ftp
     * @throws Exception
     */
    private void logout(FTPClient ftp) throws Exception
    {
        if (ftp == null)
        {
            return;
        }

        try
        {
            ftp.quit();
        }
        catch (Exception ignore)
        {
            System.out.println("Exception Occuered While Logging Out From SMIC FTP Site" + ignore);
            throw new ScalarException("Exception Occuered While Logging Out From SMIC FTP Site" + ignore);
        }
        ftp = null;
    }

    private void log(String message)
    {
        if (message == null) return;

        if (m_adaptorLogger != null)
        {
            synchronized (m_adaptorLogger)
            {
                m_adaptorLogger.logDebug(message + LINE_SEPARATOR);
            }
        }
        else
        {
            System.out.println(message);
        }
    }
}
